package com.grieous.wow.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grieous.wow.biz.UserBiz;
import com.grieous.wow.common.Md5Util;
import com.grieous.wow.dao.impl.UserDaoImpl;
import com.grieous.wow.entity.PageModel;
import com.grieous.wow.entity.User;

@Service("userBiz")
@Transactional
public class UserBizImpl implements UserBiz {

	@Resource
	private UserDaoImpl userDao;

	@Override
	public PageModel getUser(Integer pageSize, Integer page) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = 0;
		if (pageSize != null) {
			page = page == null ? 1 : page;
			count = userDao.findCountByCondition(map);
			map.put("startId", (page - 1) * pageSize);
			map.put("pageSize", pageSize);
		}
		List<User> list = userDao.findListByCondition(map);
		PageModel pm = PageModel.getPageModel(pageSize, page, count, list);
		return pm;
	}

	@Override
	public boolean saveUser(User user) {
		if (user != null) {
			String pwd = Md5Util.encode(user.getPassword());
			user.setPassword(pwd);
			if (user.getId() != null && !user.getId().equals("")) {
				if (userDao.update(user) == 1)
					return true;
			} else {
				if (userDao.add(user) == 1)
					return true;
			}
		}
		return false;
	}

	@Override
	public boolean delUser(int... userIds) {
		if (userIds != null && userIds.length > 0) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ids", userIds);
			if (userDao.delete(map) == userIds.length)
				return true;
		}
		return false;
	}

	@Override
	public User getUserById(int id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<User> list = userDao.findListByCondition(map);
		if (list != null && list.size() == 1) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public User login(String username, String password) {
		if (username == null || username.equals("")) {
			return null;
		}
		if (password == null || password.equals("")) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", username);
		map.put("password", Md5Util.encode(password));
		map.put("startId", 0);
		map.put("pageSize", 1);
		List<User> list = userDao.findListByCondition(map);
		if (list != null && list.size() == 1) {
			return list.get(0);
		}
		return null;
	}
}
